jQuery(document).ready(function($){

	var wboxpr_option_upload;
	var wboxpr_option_selector;

	function wboxpr_option_add_file(event, selector) {
		var upload = $(".uploaded-file"), frame;
		var $el = $(this);
		wboxpr_option_selector = selector;
		event.preventDefault();
		if ( wboxpr_option_upload ) {
			wboxpr_option_upload.open();
		} else {
						wboxpr_option_upload = wp.media.frames.wboxpr_option_upload =  wp.media({
								title: $el.data('choose'),

								button: {
										text: $el.data('update'),
															close: false
				}
			});

						wboxpr_option_upload.on( 'select', function() {
								var attachment = wboxpr_option_upload.state().get('selection').first();
				wboxpr_option_upload.close();
				wboxpr_option_selector.find('.upload').val(attachment.attributes.url);
				if ( attachment.attributes.type == 'image' ) {
					wboxpr_option_selector.find('.screenshot').empty().hide().append('<img src="' + attachment.attributes.url + '"><a class="remove-image">Remove</a>').slideDown('fast');
				}
				wboxpr_option_selector.find('.upload-button').unbind().addClass('remove-file').removeClass('upload-button').val(wboxpr_option_l10n.remove);
				wboxpr_option_selector.find('.of-background-properties').slideDown();
				wboxpr_option_selector.find('.remove-image, .remove-file').on('click', function() {
					wboxpr_option_remove_file( $(this).parents('.section') );
				});
			});

		}

				wboxpr_option_upload.open();
	}

	function wboxpr_option_remove_file(selector) {
		selector.find('.remove-image').hide();
		selector.find('.upload').val('');
		selector.find('.of-background-properties').hide();
		selector.find('.screenshot').slideUp();
		selector.find('.remove-file').unbind().addClass('upload-button').removeClass('remove-file').val(wboxpr_option_l10n.upload);
						if ( $('.section-upload .upload-notice').length > 0 ) {
			$('.upload-button').remove();
		}
		selector.find('.upload-button').on('click', function(event) {
			wboxpr_option_add_file(event, $(this).parents('.section'));
		});
	}

	$('.remove-image, .remove-file').on('click', function() {
		wboxpr_option_remove_file( $(this).parents('.section') );
    });

    $('.upload-button').click( function( event ) {
    	wboxpr_option_add_file(event, $(this).parents('.section'));
    });

});